﻿package kliment.display {
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.geom.Rectangle;
	import kliment.display.draw.DrawStyle;
	import kliment.display.draw.shape.RectangleShape;
	import kliment.display.draw.style.BitmapFillStyle;
	import kliment.layout.SpriteCanvas;
	
	/**
	 * ...
	 * @author	Kliment
	 * @version	0.0.1
	 */
	public class SpritePattern extends SpriteCanvas	{
		private var _min_width:Number = 1;
		private var _min_height:Number = 1;
		private var _max_width:Number = 1;
		private var _max_height:Number = 1;
		
		private var _width:Number = 0;
		private var _height:Number = 0;
		
		private var _onlyIncrease:Boolean = true;
		
		private var _part_bitmapData:BitmapData;
	
		private var _drawStyle:DrawStyle;
		private var _drawRectangle:Rectangle;
		private var _shape:RectangleShape;
		
		public function SpritePattern(part:*) {
			super();
			
			if (part is BitmapData) {
				_part_bitmapData = part.clone();
				_min_width = _part_bitmapData.width;
				_min_height = _part_bitmapData.height;
			} else if (part is Sprite ) {
				_part_bitmapData = new BitmapData(part.width, part.height, true, 0x000000);
				_part_bitmapData.draw(part);
			}
			_drawStyle = new DrawStyle(null, null, null, new BitmapFillStyle(_part_bitmapData, null, true, false));
			_drawRectangle = new Rectangle();
		}
		
		public function setSize(width:Number, height:Number):void {
			_width = Math.max(width, _min_width);
			_height = Math.max(height, _min_height);
			_draw();
		}
		
		private function _draw():void {
			if (_onlyIncrease) {
				super.width = _width;
				super.height = _height;
			
				if (_max_width <= _width || _max_height <= _height) {
					_max_width = Math.max(_width, _max_width);
					_max_height = Math.max(_height, _max_height);
					_drawRectangle.width = _max_width;
					_drawRectangle.height = _max_height;
					
					if (_shape) _shape.remove();
					_shape = new RectangleShape(_drawRectangle, _drawStyle);
					addChild(_shape);
				} 
			} else {
				_drawRectangle.width = _width;
				_drawRectangle.height = _height;
				
				if (_shape) _shape.remove();
				_shape = new RectangleShape(_drawRectangle, _drawStyle);
				addChild(_shape);
			}
		}
		
		override public function get width():Number { return _width; }
		override public function set width(value:Number):void {
			setSize(value, _height);
		}
		
		override public function get height():Number { return _height; }
		override public function set height(value:Number):void {
			setSize(_width, value);
		}
	}

}